<template>
  <div>
    <Search :search="search" :reset="reset">
      <template v-slot:body>
         <el-form-item label="手机号" prop="phone">
  <el-input v-model="query.phone" name="phone" clearable />
</el-form-item>
<el-form-item label="状态" prop="status">
  <el-select v-model="query.status" placeholder="请选择">
        <el-option
          v-for="item in Status"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
  </el-select>
  <!-- <el-input v-model="query.status" name="status" clearable /> -->
</el-form-item>
<el-form-item label="运营商渠道" prop="channel">
  <el-input v-model="query.channel" name="channel" clearable />
</el-form-item>
<el-form-item label="锁号状态" prop="temp_status">
  <el-select v-model="query.temp_status" placeholder="请选择">
        <el-option
          v-for="item in temp_Status"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
  </el-select>
  <!-- <el-input v-model="query.temp_status" name="temp_status" clearable /> -->
</el-form-item>
<!-- <el-form-item label="锁号时间" prop="lock_time">
  <el-input v-model="query.lock_time" name="lock_time" clearable />
</el-form-item> -->
<el-form-item label="商品编码/套餐ID" prop="commodity_code">
  <el-input v-model="query.commodity_code" name="commodity_code" clearable />
</el-form-item>
      </template>
    </Search>
    <div class="table-default">
      <Operate :show="open" >
        <template #operate>
          
            <el-button @click="importPhone">
              导入号池
            </el-button>
            <el-button  @click="downloadTemplate">下载导入模板</el-button>
        </template>
      </Operate>
      <el-table :data="tableData" class="mt-3" v-loading="loading" >
        <el-table-column prop="id" label="ID" align="center"/>
        <el-table-column prop="phone" label="手机号" align="center"/>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <div v-if="scope.row.status == 1">
              可使用
            </div>
            <div v-if="scope.row.status == 2">
              已使用
            </div>
            <div v-if="scope.row.status == 3">
              异常
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="channel" label="运营商渠道" align="center"/>
        <el-table-column prop="temp_status" label="锁号状态" align="center">
          <template #default="scope">
            <div v-if="scope.row.temp_status == 1" style="padding: 3px 0px ;background-color: #f43f5e;color: #fff;max-width: 100px;height: 40%;margin: 0 auto;border-radius: 5px;font-size: 14px;text-align: center;">
              已锁号
            </div>
            <div v-if="scope.row.temp_status == 2" style="padding: 3px 0px ;background-color: #2B842C;color: #fff;max-width: 100px;height: 40%;margin: 0 auto;border-radius: 5px;font-size: 14px;text-align: center;">
              未锁号
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="lock_time" label="锁号时间" align="center">
          <template #default="scope">
            {{ scope.row.lock_time ? scope.row.lock_time : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="commodity_code" label="商品编码/套餐ID" align="center">
          <template #default="scope">
            {{ scope.row.commodity_code ? scope.row.commodity_code : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <Update @click="open(scope.row.id)" />
            <Destroy @click="destroy(api, scope.row.id)" />
          </template>
        </el-table-column>
      </el-table>
      <Paginate />
    </div>

    <Dialog v-model="visible" :title="title" destroy-on-close>
      <Create @close="close(reset)" :primary="id" :api="api" />
    </Dialog>
    <Dialog v-model="importVisible" title="导入" destroy-on-close>
      <!-- action="http://catchadmin.test/api/selection/selection/import" -->
      <!-- https://5g.ghywkj.com.cn/api/selection/selection/import -->
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="actionApi"
        :auto-upload="false"
        :headers="{ authorization: token, 'Request-from': 'Dashboard' }"
        limit="1"
        @start="handleUploadStart"
        @success="handleUploadSuccess"
        @error="handleUploadError"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
      </el-upload>
      <div class="flex justify-end">
            <el-button type="primary" @click="importStar">导入</el-button>
      </div>
    </Dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted , ref } from 'vue'
import Create from './create.vue'
import { useGetList } from '@/composables/curd/useGetList'
import { useDestroy } from '@/composables/curd/useDestroy'
import { useOpen } from '@/composables/curd/useOpen'
import type { UploadInstance , ElMessage  } from 'element-plus'
import Message from '@/support/message'
import { env, getAuthToken } from '@/support/helper'

import * as XLSX from 'xlsx';
import http from '@/support/http'

const api = 'selection/selection'

const { data, query, search, reset, loading } = useGetList(api)
const { destroy, deleted } = useDestroy()
const { open, close, title, visible, id } = useOpen()

const temp_Status = ref([{ value: 1, label: '已锁号' },{value:2,label:'未锁号'}])
const Status = ref([{ value: 1, label: '可使用' },{value:2,label:'已使用'},{value:3,label:'异常'}])

// http://gh.oneself.icu/api/selection/selection/import
const actionApi = ref<string>('')
// let baseURL = env('VITE_BASE_URL')
const port = window.location.port;
if(port == '8080'){
  actionApi.value = 'https://5g.ghywkj.com.cn:8080/api/selection/selection/import'
  // actionApi.value = 'http://gh.oneself.icu:8080/api/selection/selection/import'
}else if(port == '8081'){
  actionApi.value = 'https://5g.ghywkj.com.cn:8081/api/selection/selection/import'
  // actionApi.value = 'http://gh.oneself.icu:8081/api/selection/selection/import'
}else if(port == '8082'){
  actionApi.value = 'https://5g.ghywkj.com.cn:8082/api/selection/selection/import'
  // actionApi.value = 'http://gh.oneself.icu:8082/api/selection/selection/import'
}else{
  actionApi.value = 'https://5g.ghywkj.com.cn/api/selection/selection/import'
  // actionApi.value = 'http://gh.oneself.icu:80/api/selection/selection/import'
}


// 导入号池
const importVisible = ref(false)
const importPhone = () => {
  importVisible.value = true
}
const token = ref<string>()
token.value = 'Bearer ' + getAuthToken()
const uploadRef = ref<UploadInstance>()
const importStar = () => {
  uploadRef.value!.submit()
}
const handleUploadStart = () => {
  // importMessage.value = '正在上传文件，请稍候...';
};
const handleUploadSuccess = (response, file, fileList) => {
  Message.success('文件导入成功');
  uploadRef.value!.clearFiles()
  importVisible.value = false
  search()
};
const handleUploadError = (err) => {
  Message.error('文件导入失败');
};


// 下载导入模板

const writeFileAsync = (workbook, filename, options) => {
    return new Promise((resolve, reject) => {
        try {
            XLSX.writeFile(workbook, filename, options);
            resolve();
        } catch (error) {
            reject(error);
        }
    });
}
const downloadTemplate = async () => {
    // 构造json
    const json = [
        {
            手机号: '',
            运营商: '',
            商品编码或套餐ID: ''
        }
    ];
 
    // 将json数据转换成excel文件
    const worksheet = XLSX.utils.json_to_sheet(json);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
 
    try {
        // 将excel 文件保存为blob
        const blob = await writeFileAsync(workbook, '模板.xlsx', { bookType: 'xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
 
        if (blob instanceof Blob) {
            // 创建下载链接
            const url = window.URL.createObjectURL(blob);
 
            // 创建隐藏的a标签，设置下载链接并触发点击
            const a = document.createElement('a');
            a.href = url;
            a.download = 'excel.template.xlsx';
            document.body.appendChild(a);
            a.click();
 
            // 释放对象url
            window.URL.revokeObjectURL(url);
 
            // 等待5秒后关闭模态框
            setTimeout(() => {
                document.body.removeChild(a);
            }, 5000);
        } else {
            throw new Error('Invalid Blob');
        }
    } catch (error) {
        //console.error('Error creating object URL:', error);
    }
  }


const tableData = computed(() => data.value?.data)

onMounted(() => {
  search()
  deleted(reset)
})
</script>
<style scoped>
.download{
  padding: 20px;
}
</style>
